﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.IO;
using System.Text.RegularExpressions;
using DflyingForum.Core.Framework;

namespace Dottext.Web.UI.Handlers
{
    /// <summary>
    ///BasePageHandlerFactory 的摘要说明
    /// </summary>
    public class BasePageHandlerFactory : IHttpHandlerFactory
    {
        public BasePageHandlerFactory()
        {
            //
            //TODO: 在此处添加构造函数逻辑
            //
        }

        public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string path)
        {
            if (IsExistedPage(path))
            {
                return PageParser.GetCompiledPageInstance(url, path, context);
            }

            if (!path.ToLower().EndsWith(".aspx"))//www.123.com/st
            {
                path = Path.Combine(path, "Default.aspx");//=>www.123.com/st/Default.aspx
            }
            url = ReplaceUrl(url);
            path = ReplaceUrl(path);
            return PageParser.GetCompiledPageInstance(url, path, context);
        }

        /// <summary>
        /// 判断当前请求的URL是否真实存在
        /// </summary>
        /// <param name="path">请求URL的相对路径</param>
        /// <returns></returns>
        private bool IsExistedPage(string path)
        {
            //容器页是已经存在的
            if (path.ToLower().IndexOf("Default.aspx") > 0)
            {
                return true;
            }

            return false;
        }

        /// <summary>
        /// 把实际不存在的页面名称转换成已经真实存在的default.aspx 
        /// 例如:default2.aspx实际不存在,则把default2.aspx转换成default.aspx
        /// </summary>
        /// <param name="input">当前请求的但实际并不存在的URL 例如:default2.aspx</param>
        /// <returns></returns>
        private string ReplaceUrl(string input)//没有引入错误页,而且这里会把已存在的替换
        {
            //int lastIndex = input.LastIndexOf('/');
            //string filename = input.Substring(lastIndex + 1);
            //string directory = input.Substring(0, input.Length - lastIndex - 1);
            //string[] allFile = Directory.GetFiles(HttpContext.Current.Server.MapPath(directory)).Where(s => s.ToLower().EndsWith(".aspx")).ToArray();
            //if (allFile.Count(s => s.LastIndexOf(filename) > 0) > 0)
            //{
            //    return input;
            //}
            //else
            //{
                // Regex search and replace
                RegexOptions options = RegexOptions.None;
                Regex regex = new Regex(@"\w+.aspx", options);
                string replacement = @"Default.aspx";
                string result = regex.Replace(input, replacement);
                return result;
            //}
        }

        public void ReleaseHandler(IHttpHandler handler)
        {

        }
    }
}